package com.deng.cloudcommons.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
/**
 * @author 邓天天
 * @date 2021/4/5 21:42
 */
@Getter
@Setter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> {
    private Result(){}

    private Integer errorCode;
    private String errorMsg;
    private Long executionTime;
    private String machineName;
    private Date time;
    private T data;

    public static <T> Result<T> success(T object) {
        Result<T> result = new Result<>();
        result.setData(object);
        result.setErrorCode(0);
        result.setErrorMsg("执行成功");
        result.setMachineName(getMachine());
        return result;
    }
    public static <T> Result<T> success() {
        return success(null);
    }

    public static <T> Result<T> error() {
        Result<T> result = new Result<>();
        result.setErrorCode(-1);
        result.setErrorMsg("执行失败");
        result.setMachineName(getMachine());
        return result;
    }

    public Result<T> data(T o) {
        this.setData(o);
        return this;
    }

    public Result<T> errorCode(Integer errorCode) {
        this.setErrorCode(errorCode);
        return this;
    }

    public Result<T> errorMsg(String msg) {
        this.setErrorMsg(msg);
        return this;
    }

    public Result<T> executionTime(long executionTime) {
        this.setExecutionTime(executionTime);
        return this;
    }



    public static String getMachine() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "获取机器名字失败";
        }
    }
}
